//
//  HomeViewController.m
//  买家版首页
//
//  Created by 王天义 on 16/8/14.
//  Copyright © 2016年 TYWang. All rights reserved.
//
#import "HomeViewController.h"
#import "HomeTopScrollView.h"
#import "HomeGongNengCell.h"
#import "HomeReXiaoCell.h"
#import "HomeXiaoXiViewController.h"
#import "HomeTableViewCell.h"
#import "SDCycleScrollView.h"
#import "AddressViewController.h"
#import "CommodityViewController.h"
#import "HomeCollectionCell.h"
#import "HomeModel.h"
#import "HomeSixProductModel.h"
#import "WelcomViewController.h"
#import "HomeGongGaoViewController.h"
#import "HomeXiaoXiModel.h"
#import "ShopingCartViewController.h"
#import "MyProductsTool.h"


@interface HomeViewController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,SDCycleScrollViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate>
{
    float _lng; //经度
    float _lat; //维度
    NSString *_articlesStr;   //滚动公告详情
    NSNumber *_articlesId;    //滚动公告Id
    NSInteger _ProductId;    //热销商品Id
}

@property (nonatomic ,strong)NSMutableArray *datas;        //首页数据源
@property (nonatomic ,strong)NSMutableArray *storeDatas;    //商店数据源
@property (nonatomic ,strong)NSMutableArray *products;      //热销商品数据源
@property (nonatomic ,strong)NSMutableArray *articles;      //滚动公告详情数据源
@property (nonatomic ,strong)NSMutableArray *articleIds;    //滚动公告Id数据源

@property (nonatomic ,strong)UITableView *homeTableView;    //主tableView
@property (nonatomic,strong)CommodityViewController *commodityVC;  //商品详情
@property (nonatomic,strong)UICollectionView *homeCollectionView;    //商品
@property (nonatomic ,strong)HomeCollectionCell *shopCell;          //热销商品列表
@property (nonatomic, strong)NSString *dingweiStr;                  //左上角定位字段
@property (nonatomic ,strong)BMKLocationService *locService;        //定位服务
@property (nonatomic,strong)BMKGeoCodeSearch *geocodesearch;        //GEO搜索服务

@end

@implementation HomeViewController

#pragma mark --- 懒加载
- (NSString *)dingweiStr{
    if (_dingweiStr == nil) {
        _dingweiStr = @"点击定位";
    }
    return _dingweiStr;
}

- (NSMutableArray *)datas{
    if (_datas == nil) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}

- (NSMutableArray *)storeDatas{
    if (_storeDatas == nil) {
        _storeDatas = [NSMutableArray array];
    }
    return _storeDatas;
}

- (NSMutableArray *)products{
    if (_products == nil) {
        _products = [NSMutableArray array];
    }
    return _products;
}

- (NSMutableArray *)articles{
    if (_articles == nil) {
        _articles = [NSMutableArray array];
    }
    return _articles;
}

- (NSMutableArray *)articleIds{
    if (_articleIds == nil) {
        _articleIds = [NSMutableArray array];
    }
    return _articleIds;
}
#pragma mark --- 视图将要出现
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getMessageRequest];
    self.tabBarController.tabBar.hidden = NO;
    //创建一个消息对象
    NSNotification * noticelayoutRefresh = [NSNotification notificationWithName:@"layoutRefresh" object:nil userInfo:nil];
    //发送消息
    [[NSNotificationCenter defaultCenter]postNotification:noticelayoutRefresh];
}
#pragma mark - 视图将要消失
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    _locService.delegate = nil; // 不用时，置nil
    _geocodesearch.delegate = nil; // 不用时，置nil
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self BaiDuLocation];
    //初始化百度地图
    
    //获取通知中心单例对象
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    //添加当前类对象为一个观察者，name和object设置为nil，表示接收一切通知
    [center addObserver:self selector:@selector(addressChange:) name:@"addressChange" object:nil];
    self.title = @"首页";
    
    [self creatNavigationBar];//设置导航栏
    [self creatHomeTableview]; //设置视图
    [self creatReXiaoProducts];//设置热销商品
    
    self.homeTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getMoreRequest)];    //    默认【下拉刷新】
    [self.homeTableView.mj_header beginRefreshing];
}

- (void)BaiDuLocation{
    // 此处记得不用的时候需要置nil，否则影响内存的释放
    _locService = [[BMKLocationService alloc]init];//定位功能的初始化
    _locService.delegate = self;    //启动LocationService
    [_locService startUserLocationService];//启动定位服务
    _geocodesearch = [[BMKGeoCodeSearch alloc] init];//编码服务的初始化(就是获取经纬度,或者获取地理位置服务)
    _geocodesearch.delegate = self;
}

- (void)getMoreRequest{
    
    [self getMessageRequest]; //刷新未读消息
    [self getNearStore];
}

#pragma mark --- 设置NavigationBar
- (void)creatNavigationBar{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:self.dingweiStr style:UIBarButtonItemStyleDone target:self action:@selector(homeDingWeiBtnClick)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImageName:@"notification-bell" highImageName:@"notification-bell" target:self action:@selector(homeXiaoXiBtnClick)];
    self.navigationItem.rightBarButtonItem.badgeCenterOffset = CGPointMake(-8, 0);
}

#pragma mark --- 创建HomeTableView
- (void)creatHomeTableview{
    if (self.homeTableView == nil) {
        self.homeTableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0, XNWindowWidth, XNWindowHeight - 64) style:UITableViewStyleGrouped];
    }
    self.homeTableView.delegate = self;
    self.homeTableView.dataSource = self;
    self.homeTableView.showsVerticalScrollIndicator = NO;
    self.homeTableView.backgroundColor = GDJColor(243, 243, 243);
    self.homeTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.view = self.homeTableView;
    [self creatHomeTopScrollView];     //设置顶部轮播图
}

#pragma mark - 设置热销商品视图
- (void)creatReXiaoProducts{
    if ([RegularExpressions isBlankInteger:GETShopId]) {
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 150, 300)];
        btn.backgroundColor = [UIColor clearColor];
        btn.titleLabel.textColor = [UIColor whiteColor];
        btn.enabled = NO;
        //        btn.centerX = self.view.centerX;
        //        [btn setTitle:@"附近无可送货超市" forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"附近无商店"] forState:0];
        self.homeTableView.tableFooterView = btn;
    }else{
        self.homeTableView.tableFooterView = [self creatHomeCollectionView];
    }
}

#pragma mark -- 创建广告滚动视图跳转到商品详情
- (void)creatHomeTopScrollView {
    //     需要加载网络图片，打开注释
    //    [CQNetWorkTools GETWithURL:URL par:nil success:^(id responseObject) {
    //        NSArray *arr = [responseObject objectForKey:@"banners"];
    //        for (NSDictionary *dic in arr) {
    //            NSString *str = [dic objectForKey:@"imgUrl"];
    //            [dataSource addObject:str];
    //        }
    //    } filed:^(NSError *error) {
    //        NSLog(@"%@",error);
    //    }];
    
    // 采用本地图片实现
    NSArray *imageNames = @[@"0e1d57b5ff1200000162ad3320f7.jpg",
                            @"18G5s8PICfyX_1024.jpg",
                            @"18G58dsICfyX_1024.jpg",
                            @"18G58PICfyX_1024.jpg"
                            // 本地图片请填写全名
                            ];
    //
    // 本地加载 --- 创建不带标题的图片轮播器
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 64, XNWindowWidth, (XNWindowHeight - 64 - 49) / 3) shouldInfiniteLoop:YES imageNamesGroup:imageNames];
    cycleScrollView.delegate = self;
    cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated;
    cycleScrollView.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    cycleScrollView.tag = 0;
    cycleScrollView.backgroundColor = GDJColor(243, 243, 243);
    self.homeTableView.tableHeaderView = cycleScrollView;
    //         --- 轮播时间间隔，默认1.0秒，可自定义
    //cycleScrollView.autoScrollTimeInterval = 4.0;
}

#pragma mark - 促销商品
- (UICollectionView *)creatHomeCollectionView{
    //创建布局类
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //最小水平间隙
    layout.minimumInteritemSpacing = 0;
    //最小垂直间隙
    layout.minimumLineSpacing = 3;
    
    //设置单元格的大小
    layout.itemSize = CGSizeMake(XNWindowWidth / 2 - 2, XNWindowWidth / 2 + 70);
    
    
    _homeCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, XNWindowWidth, (XNWindowWidth / 2 + 70) * 3 + 110) collectionViewLayout:layout];
    _homeCollectionView.delegate = self;
    _homeCollectionView.dataSource = self;
    _homeCollectionView.backgroundColor = [UIColor clearColor];
    _homeCollectionView.showsVerticalScrollIndicator = NO;
    _homeCollectionView.showsHorizontalScrollIndicator = NO;
    //xib注册
    [_homeCollectionView registerNib:[UINib nibWithNibName:@"HomeCollectionCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"HomeCollectionCellID"];
    // 注册尾部
    [_homeCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footid"];
    //    //指定尾部视图的大小
    layout.footerReferenceSize = CGSizeMake(0, 50);
    return _homeCollectionView;
}

#pragma mark -- tableView数据源代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"HomeTableViewCellID";
    BOOL nibsRegistered = NO;
    if (!nibsRegistered) {
        UINib *nib = [UINib nibWithNibName:NSStringFromClass([HomeTableViewCell class]) bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:CellIdentifier];
        nibsRegistered = YES;
    }
    HomeTableViewCell *cell = (HomeTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    HomeModel *model = self.storeDatas.lastObject;
    if (self.storeDatas.count != 0) {
        cell.storeNameLabel.text = model.ShopName;
        cell.storeDistanceLabel.text = [NSString stringWithFormat:@"距您%@米",model.Distance];
        cell.storeLocationLabel.text = [NSString stringWithFormat:@"商店地址:%@",model.CompanyAddress];
        cell.storeLocationLabel.numberOfLines = 0;
        cell.upSendLabel.text = [NSString stringWithFormat:@"%@元起送",model.QiSongJia];
        
        cell.monthSellLabel.text = [NSString stringWithFormat:@"月售%@单",model.SaleCounts];
        
        NSString *urlStr = [NSString stringWithFormat:@"%@%@",ReleaseORDebug,model.Logo];
        [cell.storeImageView sd_setImageWithURL:[NSURL URLWithString:urlStr]];
        cell.storeImageView.hidden = NO;

    }
       return cell;
}


#pragma mark --- 返回组头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    //
    //    HomeGongNengCell * gongnengCell = [[NSBundle mainBundle]loadNibNamed:@"HomeGongNengCell" owner:nil options:nil].lastObject;
    //
    //    [gongnengCell.homeQG1 addTarget:self action:@selector(homeQG1BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    //    [gongnengCell.homeQG2 addTarget:self action:@selector(homeQG1BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    //    [gongnengCell.homeQG3 addTarget:self action:@selector(homeQG1BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    //    [gongnengCell.homeQG4 addTarget:self action:@selector(homeQG1BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    //
    // 网络加载 --- 创建只上下滚动展示文字的轮播器
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, XNWindowWidth, 25.5) delegate:self placeholderImage:nil];
    cycleScrollView.scrollDirection = UICollectionViewScrollDirectionVertical;
    cycleScrollView.titleLabelTextColor = [UIColor blackColor];
    cycleScrollView.titleLabelBackgroundColor = [UIColor whiteColor];
    cycleScrollView.exclusiveTouch = NO;
    cycleScrollView.onlyDisplayText = YES;
    cycleScrollView.titlesGroup = [self.articles copy];
    cycleScrollView.tag = 1;
    //    [gongnengCell.gunDongTitle addSubview:cycleScrollView];
    
    //    return gongnengCell;
    return cycleScrollView;
    //
}

#pragma mark -- 返回组头的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    //    return XNWindowHeight / 3 + 60 ;
    if (GETShopId) {
        return 25.5;
    }
    return 0;
}

#pragma mark -- 返回组尾视图
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if ([RegularExpressions isBlankInteger:GETShopId]) {
        return nil;
    }else{
        HomeReXiaoCell * reXiaoCell = [[NSBundle mainBundle]loadNibNamed:@"HomeReXiaoCell" owner:nil options:nil].lastObject;
        return reXiaoCell;
    }
}

#pragma mark -- 组尾的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    //    如果附近没有供货超市,隐藏组尾
    if ([RegularExpressions isBlankInteger:GETShopId]) {
        return 0;
    }else{
        return 30 ;
    }
}

#pragma mark -- tabbleViewCell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //    如果附近没有供货超市,隐藏Cell
    if ([RegularExpressions isBlankInteger:GETShopId]) {
        return 0;
    }else{
          return XNWindowHeight / 4;
    }
}

#pragma mark -- tabbleViewCell点击代理
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.tabBarController.selectedIndex = 1;//点击cell跳转到分类页面
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    //设置高度
    //    if (self.products.count % 2) {
    //       collectionView.height =(self.products.count / 2 + 1) * (XNWindowWidth / 2 + 70) + 110;
    //    }else{
    //       collectionView.height = self.products.count / 2 * (XNWindowWidth / 2 + 70) + 110;
    //    }
    return self.products.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HomeCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomeCollectionCellID" forIndexPath:indexPath];
    cell.datas = self.products;
    
    if (self.products.lastObject) {
        HomeSixProductModel *model = self.products[indexPath.row];
        [cell.commodityPic sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",ReleaseORDebug,model.ImagePath]]];
        cell.commodityPic.hidden = NO;
        cell.commodityName.text = model.ProductName;
        cell.commodityName.font = [UIFont systemFontOfSize:14];
        cell.commodityName.numberOfLines = 0;
        cell.commodityPirce.text = [NSString stringWithFormat:@"%@元",model.MinSalePrice];
        cell.commodityYuanPirce.text = [NSString stringWithFormat:@"原价%@元",model.MarketPrice];
        cell.commoditySales.text = [NSString stringWithFormat:@"销量:%ld",(long)model.SaleCounts];
        
        _ProductId = model.Id;
        
        [cell.jiaBtn addTarget:self action:@selector(addBtn:) forControlEvents:UIControlEventTouchUpInside];
        [cell.jianBtn addTarget:self action:@selector(jianBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        cell.tag = model.Id;
        cell.jianBtn.tag = model.Id;
        cell.jiaBtn.tag = model.Id;
        cell.commodityNumLabel.tag = model.Id;
        self.shopCell = cell;
    }
    return cell;
}

#pragma mark -- HomecollectionView代理
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    DLog(@"商铺页面，点击商品");
    
    HomeSixProductModel *model = self.products[indexPath.row];
    if (!_commodityVC) {
        _commodityVC  = [[CommodityViewController alloc]init];
    }
    _commodityVC.isSale = YES;
    _commodityVC.ProductId = [NSString stringWithFormat:@"%ld",(long)model.Id];
    [self.navigationController pushViewController:_commodityVC animated:YES];
}



#pragma mark --- 返回collection头部和尾部视图

// 返回每一组的头部或尾部视图
// 会自动的在每一组的头部和尾部加上这个视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    // 如果当前想要的是头部视图
    // UICollectionElementKindSectionHeader是一个const修饰的字符串常量,所以可以直接使用==比较
    if (kind == UICollectionElementKindSectionHeader) {
        return 0;
    } else { // 返回每一组的尾部视图
        UICollectionReusableView *footerView =  [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footid" forIndexPath:indexPath];
        
        UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 10, XNWindowWidth, 40)];
        [button setBackgroundImage:[UIImage imageNamed:@"查看更多商品"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(more) forControlEvents:UIControlEventTouchUpInside];
        [footerView addSubview:button];
        
        return footerView;
    }
}

#pragma mark - SDCycleScrollViewDelegate(滚动公告)
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    if (cycleScrollView.tag == 0) {
        
    }else if(cycleScrollView.tag == 1){
        HomeGongGaoViewController *vc = [[HomeGongGaoViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
        vc.ArticleId = self.articleIds[index];
    }
    DLog(@"---点击了第%ld条公告", (long)index);
}


#pragma mark -- 按钮点击

- (void)homeQG1BtnClick:(id)sender{
    DLog(@"抢购");
}

- (void)homeDingWeiBtnClick{

    
    CLAuthorizationStatus type = [CLLocationManager authorizationStatus];
    if (![CLLocationManager locationServicesEnabled] || type == kCLAuthorizationStatusDenied){
        NSLog(@"定位功能不可用，提示用户或忽略");
        //读取本地数据
        NSString * isPositioning = [[NSUserDefaults standardUserDefaults] valueForKey:@"isPositioning"];
        if (isPositioning == nil)//提示
        {

            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"为了更好的体验,请到设置->隐私->定位服务中开启!" preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"立即开启" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [alert dismissViewControllerAnimated:YES completion:nil];
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                //适配iOS7 ,跳入系统设置界面
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"]];
            }]];
            [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [alert dismissViewControllerAnimated:YES completion:nil];
            }]];
            [self presentViewController:alert animated:YES completion:nil];
            

        }
    }else{
        
        NSUserDefaults * userLogon = [NSUserDefaults standardUserDefaults];
        NSString * isSignin_String = [userLogon objectForKey:LOGIN_STATUS];
        NSLog(@"等没等。。。%@",isSignin_String);
        if ([isSignin_String isEqualToString:@"未登录"]) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还没有登录,请先登录后再执行操作!" preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"前去登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [alert dismissViewControllerAnimated:YES completion:nil];
                WelcomViewController *welcomeVC = [[WelcomViewController alloc]init];
                UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:welcomeVC];
                [UIApplication sharedApplication].keyWindow.rootViewController = nav;
            }]];
            [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [alert dismissViewControllerAnimated:YES completion:nil];
            }]];
            [self presentViewController:alert animated:YES completion:nil];
            
        }else if([isSignin_String isEqualToString:@"已登录"]){
            AddressViewController *addressVC = [[AddressViewController alloc]init];
            [self.navigationController pushViewController:addressVC animated:YES];
        }
    }
    

    
    /**判断是否登录
     */
   
}
#pragma mark -- 消息
- (void)homeXiaoXiBtnClick{
    
    /**判断是否登录
     */
    NSUserDefaults * userLogon = [NSUserDefaults standardUserDefaults];
    NSString * isSignin_String = [userLogon objectForKey:LOGIN_STATUS];
    NSLog(@"等没等。。。%@",isSignin_String);
    if ([isSignin_String isEqualToString:@"未登录"]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还没有登录,请先登录后再执行操作!" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"前去登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alert dismissViewControllerAnimated:YES completion:nil];
            WelcomViewController *welcomeVC = [[WelcomViewController alloc]init];
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:welcomeVC];
            [UIApplication sharedApplication].keyWindow.rootViewController = nav;
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alert dismissViewControllerAnimated:YES completion:nil];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        
    }else if([isSignin_String isEqualToString:@"已登录"]){
        HomeXiaoXiViewController *homeXiaoXiVC = [[HomeXiaoXiViewController alloc]init];
        [self.navigationController pushViewController:homeXiaoXiVC animated:YES];
    }
}

#pragma mark -- 选择地址通知回调方法
- (void)addressChange:(NSNotification *)sender{
    NSDictionary *dict = sender.userInfo;
    _lng = [dict[@"Lng"] floatValue];
    _lat = [dict[@"Lat"] floatValue];
    self.dingweiStr = dict[@"ShotAddress"];
    [[NSUserDefaults standardUserDefaults]setObject:self.dingweiStr forKey:@"LeftAddress"];
    self.navigationItem.leftBarButtonItem.title = self.dingweiStr;
    [self.homeTableView.mj_header beginRefreshing];    // 马上进入刷新状态
}

#pragma mark -- 添加到购物车
- (void)addBtn:(id)sender {
    /**判断是否登录
     */
    NSUserDefaults * userLogon = [NSUserDefaults standardUserDefaults];
    NSString * isSignin_String = [userLogon objectForKey:LOGIN_STATUS];
    if ([isSignin_String isEqualToString:@"未登录"]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还没有登录,请先登录后再执行操作!" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"前去登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alert dismissViewControllerAnimated:YES completion:nil];
            WelcomViewController *welcomeVC = [[WelcomViewController alloc]init];
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:welcomeVC];
            [UIApplication sharedApplication].keyWindow.rootViewController = nav;
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alert dismissViewControllerAnimated:YES completion:nil];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        
    }else if([isSignin_String isEqualToString:@"已登录"]){
        
        UIButton *btn = (UIButton *)sender;
        NSDictionary *dicStr = @{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"ProductId":[NSNumber numberWithInteger:btn.tag],@"Count":[NSNumber numberWithInteger:[MyProductsTool queryByCondition:btn.tag] + 1]};
        
        [CQNetWorkTools POSTWithURL:PostOperationShoppingCar par:dicStr success:^(id responseObject) {
            if ([[responseObject objectForKey:@"Err"] intValue]) {
                //            NSLog(@"%@",[responseObject objectForKey:@"ErrMsg"]);
                [SVProgressHUD  showWithStatus:[responseObject objectForKey:@"msg"]];
                [self performSelector:@selector(dismiss) withObject:nil afterDelay:2];
                
            }else{
                //            [self createRedPoint];
                DLog(@"加入成功");
                [MyProductsTool ClickJiaJianProduct:btn.tag andCount:[MyProductsTool queryByCondition:btn.tag] + 1 blockcompletion:^(BOOL updata) {
                    DLog(@"数据库+1");
                }];
                
                NSDictionary *dict = @{@"tag":[NSNumber numberWithInteger:btn.tag]};
                //创建一个消息对象
                NSNotification * notice = [NSNotification notificationWithName:@"productsJiaChange" object:nil userInfo:dict];
                //发送消息
                [[NSNotificationCenter defaultCenter]postNotification:notice];
            }
        } filed:^(NSError *error) {
            DLog(@"失败===%@", error);
            [SVProgressHUD  showWithStatus:@"请检查网络"];
            [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
        }];
    }
}

#pragma mark -- 减少到购物车
- (void)jianBtn:(id)sender {
    
    /**判断是否登录
     */
    NSUserDefaults * userLogon = [NSUserDefaults standardUserDefaults];
    NSString * isSignin_String = [userLogon objectForKey:LOGIN_STATUS];
    NSLog(@"等没等。。。%@",isSignin_String);
    if ([isSignin_String isEqualToString:@"未登录"]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还没有登录,请先登录后再执行操作!" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"前去登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alert dismissViewControllerAnimated:YES completion:nil];
            WelcomViewController *welcomeVC = [[WelcomViewController alloc]init];
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:welcomeVC];
            [UIApplication sharedApplication].keyWindow.rootViewController = nav;
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alert dismissViewControllerAnimated:YES completion:nil];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        
    }else if([isSignin_String isEqualToString:@"已登录"]){
        UIButton *btn = (UIButton *)sender;
        NSDictionary *dicStr = @{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"ProductId":[NSNumber numberWithInteger:btn.tag],@"Count":[NSNumber numberWithInteger:[MyProductsTool queryByCondition:btn.tag] - 1]};
        
        [CQNetWorkTools POSTWithURL:PostOperationShoppingCar par:dicStr success:^(id responseObject) {
            if ([[responseObject objectForKey:@"Err"]integerValue] != 0) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[responseObject objectForKey:@"ErrMsg"] preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [alert addAction:action1];
                [self presentViewController:alert animated:YES completion:^{
                }];
            }else {
                [MyProductsTool ClickJiaJianProduct:btn.tag andCount:[MyProductsTool queryByCondition:btn.tag] - 1 blockcompletion:^(BOOL updata) {
                    DLog(@"数据库-1");
                }];
                
                NSDictionary *dict = @{@"tag":[NSNumber numberWithInteger:btn.tag]};
                //创建一个消息对象
                NSNotification * notice = [NSNotification notificationWithName:@"productsJianChange" object:nil userInfo:dict];
                //发送消息
                [[NSNotificationCenter defaultCenter]postNotification:notice];
            }
        } filed:^(NSError *error) {
            DLog(@"失败===%@", error);
            [SVProgressHUD  showWithStatus:@"请检查网络"];
            [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
        }];
        
    }
}

#pragma mark -- 跳转到分类
- (void)more{
    self.tabBarController.selectedIndex = 1;
}

#pragma mark -- 百度地图代理方法
/**
 *在将要启动定位时，会调用此函数
 */
- (void)willStartLocatingUser{
    DLog(@"willStartLocatingUser");
}

/**
 *在停止定位后，会调用此函数
 */
- (void)didStopLocatingUser{
    
}
/**
 *定位失败后，会调用此函数
 *@param error 错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error{
    DLog(@"error:%@",error);
}

- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    [_locService stopUserLocationService];
    
    //——————————初始化反地理编码类————————————
    //注意：必须先初始化地理编码类
    BMKGeoCodeSearch *_geoCodeSearch = [[BMKGeoCodeSearch alloc]init];
    _geoCodeSearch.delegate = self;
    //初始化反地理编码类
    BMKReverseGeoCodeOption *reverseGeoCodeOption= [[BMKReverseGeoCodeOption alloc] init];
    //需要反地理编码的坐标位置
    reverseGeoCodeOption.reverseGeoPoint = CLLocationCoordinate2DMake(_locService.userLocation.location.coordinate.latitude, _locService.userLocation.location.coordinate.longitude);
    // 调用反地址编码方法，让其在代理方法中输出
    BOOL flag = [_geoCodeSearch reverseGeoCode:reverseGeoCodeOption];
    if (!flag) {
        [_locService startUserLocationService];
        
    }else {
        DLog(@"success");
        
    }
    _lng = _locService.userLocation.location.coordinate.longitude;
    _lat = _locService.userLocation.location.coordinate.latitude;
}

-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    if (error == 0) {
        
        if ([RegularExpressions isBlankString:result.addressDetail.streetName]) {
            
            //初始化提示框；
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在设置中开启定位" preferredStyle: UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
            
            //弹出提示框；
            [self presentViewController:alert animated:true completion:^{
                //重新定位
                [self.homeTableView.mj_header beginRefreshing];
            }];
            self.dingweiStr = @"点击定位";
        }else{
            self.dingweiStr = result.addressDetail.streetName;
            [[NSUserDefaults standardUserDefaults]setObject:self.dingweiStr forKey:@"LeftAddress"];
        }
        self.navigationItem.leftBarButtonItem.title = self.dingweiStr;
        
    }
}

#pragma mark --- 获取消息

- (void)getMessageRequest{
    
    /**判断是否登录
     */
    NSUserDefaults * userLogon = [NSUserDefaults standardUserDefaults];
    NSString * isSignin_String = [userLogon objectForKey:LOGIN_STATUS];
    NSLog(@"等没等。。。%@",isSignin_String);
    if([isSignin_String isEqualToString:@"已登录"]){
        NSDictionary *par = @{@"ShouJiHao":GETPHONE,
                              @"Token":GETTOKEN,
                              @"Duuid":GETUUID};
        
        [CQNetWorkTools GETWithURL:GetMessageLogBySendTo par:par success:^(id responseObject) {
            if ([[responseObject objectForKey:@"Err"]integerValue] != 0) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[responseObject objectForKey:@"ErrMsg"] preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [alert addAction:action1];
                [self presentViewController:alert animated:YES completion:^{
                    
                }];
            }else {
                
                NSArray *dataArr = [responseObject objectForKey:@"MessageLogs"];
                
                for (NSDictionary *dict in dataArr) {
                    HomeXiaoXiModel *model = [HomeXiaoXiModel mj_objectWithKeyValues:dict];
                    if (!model.IsRead){
                        [self.navigationItem.rightBarButtonItem showBadge];
                        return ;
                    }
                    if (model.IsRead) {
                        [self.navigationItem.rightBarButtonItem clearBadge];
                    }
                }
            }
        } filed:^(NSError *error) {
            DLog(@"失败===%@", error);
        }];
    }
}
#pragma mark --- 获取最近店铺请求

- (void)getNearStore{
    
    NSDictionary *par =
    @{@"Lng":[NSNumber numberWithFloat:_lng],
      @"Lat":[NSNumber numberWithFloat:_lat]};
    NSLog(@"%@",par);
    [CQNetWorkTools GETWithURL:GetNearlyStore par:par success:^(id responseObject) {
        if ([[responseObject objectForKey:@"Err"] intValue]) {
            DLog(@"%@",[responseObject objectForKey:@"ErrMsg"]);
            [SVProgressHUD  showWithStatus:[responseObject objectForKey:@"ErrMsg"]];
            [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
            //附近没有超市,清除商店Id
            [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"ShopId"];
            //附近没有超市,设置热销商品视图
            [self creatReXiaoProducts];
            
            [self.homeTableView reloadData];
            // 拿到当前的下拉刷新控件，结束刷新状态
            [self.homeTableView.mj_header endRefreshing];
        }else{
            NSDictionary *dict = [responseObject objectForKey:@"Shops"];
            [self.storeDatas removeAllObjects];
            HomeModel *model = [HomeModel mj_objectWithKeyValues:dict];
            
            
#pragma mark --- 获取到数据存到本地
            //最近店铺ID 名称 位置
            
            [[NSUserDefaults standardUserDefaults]setObject:[NSNumber numberWithInteger:model.Id] forKey:@"ShopId"];
            [[NSUserDefaults standardUserDefaults]setObject:model.ShopName forKey:@"ShopName"];
            [MyProductsTool deleteAllProductsFromSQL];//清除数据库里所有商品
            [MyProductsTool getShopCartInfoRequest];
            
            [self.storeDatas addObject:model];
            [self getTopArticle];
            [self getHotSaleProductRequest];
            //附近没有超市,设置热销商品视图
            [self creatReXiaoProducts];
            // 刷新表格
            [self.homeTableView reloadData];
            // 拿到当前的下拉刷新控件，结束刷新状态
            [self.homeTableView.mj_header endRefreshing];
            
        }
    } filed:^(NSError *error) {
        DLog(@"失败===%@", error);
        [SVProgressHUD  showWithStatus:@"请检查网络"];
        [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
        // 拿到当前的下拉刷新控件，结束刷新状态
        [self.homeTableView.mj_header endRefreshing];
    }];
}

#pragma mark --- 获取店铺销量前六的商品
- (void)getHotSaleProductRequest{
    HomeModel *model = self.storeDatas.lastObject;
    
    NSDictionary *par = @{@"ShopId":[NSNumber numberWithInteger:model.Id]};
    
    [CQNetWorkTools GETWithURL:GetHotSaleProduct par:par success:^(id responseObject) {
        NSLog(@"涂鸦%@",responseObject);
        if ([[responseObject objectForKey:@"Err"]integerValue] != 0) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[responseObject objectForKey:@"ErrMsg"] preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alert addAction:action1];
            [self presentViewController:alert animated:YES completion:^{
                
            }];
        }else{
            
            NSArray *dataArr = [responseObject objectForKey:@"Products"];
            [self.products removeAllObjects];
            
            for (NSDictionary *dict in dataArr) {
                HomeSixProductModel *model = [HomeSixProductModel mj_objectWithKeyValues:dict];
                [self.products addObject:model];
            }
            [self.homeCollectionView reloadData];
            
        }
    } filed:^(NSError *error) {
        DLog(@"失败===%@", error);
    }];
}

#pragma mark --- 获取滚动公告请求

- (void)getTopArticle{
    [CQNetWorkTools GETWithURL:GetTopArticle par:nil success:^(id responseObject) {
        
        if ([[responseObject objectForKey:@"Err"]integerValue] != 0) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[responseObject objectForKey:@"ErrMsg"] preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alert addAction:action1];
            [self presentViewController:alert animated:YES completion:^{
                
            }];
        }else{
            NSArray *dataArr = [responseObject objectForKey:@"Articles"];
            for (NSDictionary *dict in dataArr) {
                _articlesStr = [dict objectForKey:@"Title"];
                _articlesId = [dict objectForKey:@"Id"];
                [self.articles addObject:_articlesStr];
                [self.articleIds addObject:_articlesId];
                
                // 刷新表格
                [self.homeTableView reloadData];
            }
        }
    } filed:^(NSError *error) {
        DLog(@"失败===%@", error);
        //[HUD error:@"请检查网络"];
    }];
}

//消除HUD
- (void)dismiss{
    [SVProgressHUD dismiss];
}

//消除通知中心
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"addressChange" object:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"productNumChange" object:self];
}
@end
